<template>
  <div class="app-container">
    <!-- 筛选栏 -->
    <div v-show="showSearch">
      <!-- 搜索表单 -->
      <el-form :inline="true" ref="queryForm">
        <el-form-item label="标题" size="small">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入标题"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item size="small">
          <el-button type="primary" icon="el-icon-search" @click="queryDoc"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格上方按钮 -->
    <div>
      <div style="float: left; margin-bottom: 10px">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="small"
          @click="preAdd"
          >新增</el-button
        >
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="small"
          @click="deleteSelectDoc"
          >批量删除</el-button
        >
      </div>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="queryDoc"
        style="float: right"
      ></right-toolbar>
    </div>
    <!-- 信息列表 -->
    <div style="float: left; width: 100%">
      <el-table
        border
        v-loading="listLoading"
        :header-cell-style="{ background: '#FAFAFA' }"
        :data="docList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        height="75vh"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="eduCoursewareInfo.title" label="标题">
        </el-table-column>
        <el-table-column label="封面">
          <template slot-scope="scope">
            <img
              :src="scope.row.eduCoursewareInfo.cover"
              width="80"
              height="50"
            />
          </template>
        </el-table-column>
        <el-table-column label="水印">
          <template slot-scope="scope">{{
            scope.row.eduCoursewareInfo.watermark
              ? scope.row.eduCoursewareInfo.watermark
              : "---"
          }}</template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="gmtCreate"
          :show-overflow-tooltip="true"
          sortable
        >
        </el-table-column>
        <el-table-column
          label="修改时间"
          prop="gmtModified"
          :show-overflow-tooltip="true"
          sortable
        >
        </el-table-column>
        <el-table-column label="是否发布" align="center" key="status">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.coursewareStatus"
              active-text="是"
              inactive-text="否"
              active-value="1"
              inactive-value="0"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="modifyDoc(scope.row)">
              编辑
            </el-button>
            <el-button type="text" size="medium" @click="deleteDoc(scope.row)">
              删除
            </el-button>
            <el-button type="text" size="medium" @click="previewDoc(scope.row)">
              预览
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%; text-align: center; margin-top: 10px">
        <el-pagination
          @size-change="sizeChange"
          @current-change="goto"
          :current-page="page.current"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          background
          style="float: right"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 上传对话框 -->
    <el-dialog
      title="资讯上传"
      :visible.sync="uploadDialog"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="uploadForm"
        :rules="rules"
        :model="uploadForm"
        label-width="80px"
      >
        <el-row>
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="uploadForm.title"
              placeholder="请输入标题"
              maxlength="30"
            />
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="水印文字" prop="watermark">
            <el-input
              v-model="uploadForm.watermark"
              placeholder="请输入水印文字"
              maxlength="30"
            />
          </el-form-item>
        </el-row>
      </el-form>
      <el-row>
        <el-col :span="12">
          <el-upload
            ref="uploadImg"
            :on-remove="handleVodRemoveImg"
            :action="upload.imgUrl"
            :limit="1"
            :auto-upload="true"
            :on-success="afterUploadImg"
            accept=".jpg, .jpeg, .png, .JPG, .JPEG"
            list-type="picture"
          >
            <el-button size="small" type="success">选取封面</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/jpeg/png文件
            </div>
          </el-upload>
        </el-col>
        <el-col :span="12">
          <el-upload
            ref="uploadPdf"
            :on-remove="handleVodRemoveDoc"
            :limit="1"
            accept=".pdf"
            :action="upload.pdfUrl"
            :file-list="uploadForm.file"
            :auto-upload="true"
            :on-success="afterUploadPdf"
          >
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传PDF文件<br />进度条右方出现绿色√，才能点击确认按钮，请耐心等待
            </div>
          </el-upload>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="submitUpload"
          :disabled="
            uploadForm.coursewareSourceUrl == '' || uploadForm.cover == ''
          "
          :loading="uploadLoading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      title="资讯信息修改"
      :visible.sync="modifyDialog"
      width="30%"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="modifyForm" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="modifyForm.title"
            placeholder="请输入标题"
            maxlength="30"
          />
        </el-form-item>
        <el-form-item label="水印文字" prop="watermark">
          <el-input
            v-model="modifyForm.watermark"
            placeholder="请输入水印文字"
            maxlength="30"
          />
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-upload
            ref="modifyImg"
            :action="upload.imgUrl"
            :limit="1"
            :auto-upload="true"
            :on-success="afterModifyImg"
            accept=".jpg, .jpeg, .png, .JPG, .JPEG"
          >
            <img
              :src="modifyForm.cover"
              width="100"
              height="100"
              slot="trigger"
            />
          </el-upload>
        </el-form-item>
        <!-- 修改pdf -->
        <el-form-item label="文件" prop="coursewareSourceUrl">
          <el-upload
            ref="modifyPdf"
            :action="upload.pdfUrl"
            :limit="1"
            accept=".pdf"
            :auto-upload="true"
            :on-success="afterModifyPdf"
          >
            <el-button slot="trigger" size="small" type="primary"
              >点击修改</el-button
            >
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyDialog = false">取 消</el-button>
        <el-button type="primary" @click="updateDoc()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 预览pdf对话框 -->
    <el-dialog title="预览" :visible.sync="previewDialog">
      <!-- <canvas id="pdf-canvas"></canvas> -->
      <iframe
        id="pdf-iframe"
        :src="pdfUrl"
        width="100%"
        height="600px"
        frameborder="0"
      ></iframe>
    </el-dialog>
  </div>
</template>

<script>
import {
  removeCourseware,
  addCourseware,
  updateCoursewareStatus,
  updateCourseware,
  queryCoursewareList,
} from "@/api/courseware";
import { getCategory } from "@/api/classification";
import { mapGetters } from "vuex";
export default {
  name: "document",
  computed: {
    ...mapGetters(["companyId"]),
  },
  created: function () {
    this.queryDoc();
  },
  data: function () {
    return {
      //级联分类列表
      typeOptions: [],
      //上传加载遮罩
      uploadLoading: false,
      //表格加载遮罩
      listLoading: "false",
      //选中的分类id
      activeTypeId: "",
      //搜索表单
      queryParams: {
        title: "",
        gradeId: "", //等级id
        courseId: "",
        kind: "2",
      },
      //类型列表
      kindList: [
        { value: "0", label: "新型学徒" },
        {
          value: "1",
          label: "重点用工",
        },
        {
          value: "2",
          label: "技能提升",
        },
      ],
      //分页设置
      page: {
        current: 1,
        total: 0,
        size: 10,
      },
      //文件列表
      docList: [],
      //已选删除列表
      selectDocList: [],
      //上传对话框
      uploadDialog: false,
      //上传表单
      uploadForm: {},
      //上传设置
      upload: {
        // // 设置上传的请求头部
        // headers: { Authorization: "Bearer " + getToken() },

        //图片上传的地址
        imgUrl:
          process.env.BASE_API + "/coursewareOss/uploadOssCoursewareCover",
        // PDF上传的地址
        pdfUrl: process.env.BASE_API + "/coursewareOss/uploadOssCoursewareFile",
      },
      //修改的对话框
      modifyDialog: false,
      //修改的表单
      modifyForm: {
        id: "",
        cover: "",
        description: "",
        title: "",
        watermark: "",
        courseId: "", //分类id(资讯使用公司id)
        gradeId: "",
        videoCourseId: "0", //视频课程id
        chapterId: "0", //章节id
        kind: "2", //类型
      },
      //是否显示搜索表单
      showSearch: true,
      //表单验证
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
      },
      previewDialog: false,
      pdfUrl: "",
    };
  },
  methods: {
    //获取文件列表
    queryDoc: function () {
      let params = this.queryParams;
      let that = this;
      this.listLoading = true;
      //表格数据列表
      queryCoursewareList(
        params,
        this.page.current,
        this.page.size,
        this.companyId
      ).then((res) => {
        const data = res.data;
        that.page.total = data.total;
        that.docList = data.reslist;
        this.listLoading = false;
      });
      //分类列表
      getCategory(0, this.companyId).then((res) => {
        const data = res.data;
        this.typeOptions = this.deleteChildren(data.resList);
      });
    },
    //删除类别列表中的空childrenList[]
    deleteChildren(arr) {
      let childs = arr;
      for (let i = childs.length; i--; i > 0) {
        if (childs[i].childrenList) {
          if (childs[i].childrenList.length) {
            this.deleteChildren(childs[i].childrenList);
          } else {
            delete childs[i].childrenList;
          }
        }
      }
      return arr;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        title: "",
        gradeId: "",
        courseId: "",
        kind: "2",
      };
      this.queryDoc();
    },
    handleVodRemoveImg() {
      this.uploadForm.cover = "";
    },
    handleVodRemoveDoc() {
      this.uploadForm.coursewareSourceUrl = "";
    },
    //点击新增预处理
    preAdd() {
      this.uploadForm = {
        title: "", //标题
        courseId: this.companyId, //分类id(资讯使用公司id)
        gradeId: "", //等级id
        coursewareSourceUrl: "", //上传后文件URL
        coursewareSourceWatermarkUrl: "", //不用传
        watermark: "", //水印
        cover: "", //封面
        coursewareDescription: "", //简介
        videoCourseId: "0", //视频课程id
        chapterId: "0", //章节id
        kind: "2", //类型
      };
      console.log(this.uploadForm);
      //重置表单
      if (this.$refs["uploadForm"] !== undefined) {
        this.$refs["uploadForm"].resetFields();
      }
      if (this.$refs["uploadImg"] !== undefined) {
        this.$refs["uploadImg"].clearFiles();
      }
      if (this.$refs["uploadPdf"] !== undefined) {
        this.$refs["uploadPdf"].clearFiles();
      }
      this.uploadDialog = true;
    },
    //成功上传教材后
    afterUploadPdf(response) {
      this.uploadForm.coursewareSourceUrl = response.data.url;
    },
    //成功上传封面后
    afterUploadImg(response) {
      this.uploadForm.cover = response.data.url;
    },
    //新增教材信息
    submitUpload() {
      this.uploadLoading = true;
      let that = this;
      if (
        this.uploadForm.cover == "" ||
        this.uploadForm.coursewareSourceUrl == ""
      ) {
        this.$message({
          message: "请选择封面和文件",
          type: "warning",
        });
      } else {
        if (that.$refs["uploadForm"] !== undefined) {
          that.$refs["uploadForm"].validate((valid) => {
            if (valid) {
              addCourseware(that.uploadForm).then((res) => {
                if (res.success == true) {
                  this.$message({
                    message: "提交成功",
                    type: "success",
                  });
                  that.queryDoc();
                  that.uploadDialog = false;
                } else {
                  this.$message({
                    message: "提交失败",
                    type: "error",
                  });
                }
                that.uploadLoading = false;
              });
            } else {
              that.uploadLoading = false;
              return false;
            }
          });
        }
      }
    },
    //关闭对话框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },

    //发布状态修改
    handleStatusChange(row) {
      updateCoursewareStatus(row.id, row.coursewareStatus).then((res) => {
        if (res.success == true) {
          this.$message({
            message: "修改成功",
            type: "success",
          });
        } else {
          this.$message({
            message: "修改失败",
            type: "error",
          });
        }
        this.queryDoc();
      });
    },
    //删除单个文件
    deleteDoc: function (doc) {
      var self = this;
      this.$confirm("此操作将删除该文档, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var docIdArray = []; //删除列表
          docIdArray.push(doc.id);
          self.deleteDocAjax(docIdArray);
        })
        .catch(() => {});
    },
    //删除多个文件
    deleteSelectDoc: function () {
      var self = this;
      if (this.selectDocList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("此操作将删除选择的所有文档, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var docIdArray = [];
          self.selectDocList.forEach(function (doc, index) {
            docIdArray.push(doc.id);
          });
          self.deleteDocAjax(docIdArray);
        })
        .catch(() => {});
    },
    //删除Ajax请求
    deleteDocAjax: function (docIdArray) {
      var that = this;
      removeCourseware(docIdArray).then((res) => {
        if (res.success == true) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          that.page.current = 1;
          that.queryDoc();
        } else {
          this.$message({
            message: "删除失败",
            type: "error",
          });
        }
      });
    },
    //点击修改图片后
    afterModifyImg(response) {
      this.modifyForm.cover = response.data.url;
      // console.log(this.modifyForm.cover);
    },
    //点击修改pdf后
    afterModifyPdf(response) {
      this.modifyForm.coursewareSourceUrl = response.data.url;
    },
    //修改预处理
    modifyDoc(doc) {
      this.modifyForm = doc.eduCoursewareInfo;
      this.modifyForm.id = doc.id;
      this.modifyForm.kind = doc.kind;
      if (this.$refs["modifyImg"] !== undefined) {
        this.$refs["modifyImg"].clearFiles();
      }
      this.modifyDialog = true;
    },
    //提交修改
    updateDoc() {
      let that = this;
      if (this.modifyForm.title == "") {
        this.$message({
          message: "标题不能为空",
          type: "warning",
        });
      } else {
        updateCourseware(that.modifyForm).then((res) => {
          if (res.success == true) {
            this.$message({
              message: "成功",
              type: "success",
            });
            that.queryDoc();
            that.modifyDialog = false;
          } else {
            this.$message({
              message: "失败",
              type: "error",
            });
          }
        });
      }
    },
    //预览文件
    previewDoc: function (doc) {
      //加水印后的文件路径;
      let pdfUrl = doc.eduCoursewareInfo.coursewareSourceWatermarkUrl;
      //方法一，在iframe中查看：
      pdfUrl =
        "static/pdfjs/web/viewer.html?file=" + encodeURIComponent(pdfUrl);
      this.pdfUrl = pdfUrl;

      this.previewDialog = true;
    },
    //跳转页面
    goto: function (current) {
      this.page.current = current;
      this.queryDoc();
    },
    //页码改变
    sizeChange: function (size) {
      this.page.size = size;
      this.queryDoc();
    },
    //已选文件列表
    handleSelectionChange: function (val) {
      this.selectDocList = val;
    },
  },
};
</script>

<style scoped>
.category {
  margin-bottom: 20px;
}
/* 激活的类别 */
.active {
  background: #e6a23c;
  color: #fff;
}
</style>
